package com.education.user.controller;

import com.education.common.pojo.AjaxResult;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.MultipartFileUtils;
import com.education.common.utils.QiniuUtil;
import com.education.user.feign.lResourceFeign;
import com.education.user.pojo.FileUpload;
import com.education.user.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lenovo
 */
@RestController
@RequestMapping("/admin/webServer")
@CrossOrigin
public class WebServerController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private FileService fileService;
    @Autowired
    private lResourceFeign resourceFeign;
    /**
     * 七牛桶目录
     */
    private static final String QINIU_FILE_DIRECTORY = "informatization4.0/";

    /**
     * 创建token
     *
     * @return
     */
    @GetMapping("/createToken")
    public AjaxResult createToken() {
        String token = QiniuUtil.createToken();
        return AjaxResult.success(token);
    }

    @GetMapping("/deleteQiniuImage")
    public ApiReturnObject deleteQiniuImage(String fileName) {
        fileService.deleteQiniuImage(fileName);
        return new ApiReturnObject("200", "success", "");
    }

    /**
     * 智慧云课堂资源上传-流上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFile")
    public AjaxResult upload(@RequestParam(value = "file", required = false) MultipartFile file,
                             @RequestParam(value = "files", required = false) MultipartFile[] files) {
        //获得上传文件的名称
        if (null != file && !file.isEmpty()) {
            String name = "";
            name = file.getOriginalFilename();
            if (StringUtils.isEmpty(name)) {
                return AjaxResult.error("请选择文件");
            }

            //生成唯一文件名称  并拼接上传文件的名称
            String fileName = QiniuUtil.getFileName(file);
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            logger.info("后台接收完成开始上传七牛");
            //QiniuUtil.upload2Qiniu(file.getBytes(),fileName);//字节流上传
            String res = QiniuUtil.uoloapQiniuStream(inputStream, QINIU_FILE_DIRECTORY + fileName);//文件流上传

            //判断上传结果
            if (res.equals("文件上传失败")) {
                logger.error(name + " 上传失败,请重新上传！");
                return AjaxResult.error(name + " 上传失败,请重新上传！");
            }
            logger.info(name + " 上传成功！");
            return AjaxResult.success(res);
            //    多文件上传  files
        } else {
            String imageUrl = null;
            String imageUrlNo = null;
            logger.info("后台接收完成开始上传七牛");

            for (int i = 0; i < files.length; i++) {
                file = files[i];
                String name = file.getOriginalFilename();
                if (StringUtils.isEmpty(name)) {
                    return AjaxResult.error("请选择文件");
                }

                //生成唯一文件名称  并拼接上传文件的名称
                String fileName = QiniuUtil.getFileName(file);
                InputStream inputStream = null;
                try {
                    inputStream = file.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String res = QiniuUtil.uoloapQiniuStream(inputStream, QINIU_FILE_DIRECTORY + fileName);//文件流上传
                //上传成功拼接url
                if (!res.equals("文件上传失败")) {
                    if (StringUtils.isNotEmpty(imageUrl)) {
                        imageUrl = StringUtils.join(imageUrl, ";", fileName);
                    } else {
                        imageUrl = StringUtils.join(fileName);
                    }
                    logger.info(name + " 上传成功！");
                } else {
                    if (StringUtils.isNotEmpty(imageUrlNo)) {
                        imageUrlNo = StringUtils.join(imageUrlNo, ";", name);
                    } else {
                        imageUrlNo = StringUtils.join(name);
                    }
                    logger.error(name + " 上传失败,请重新上传！");
                    //return AjaxResult.error(name + " 上传失败,请重新上传！");
                }
            }
            //判断是否有上传失败的
            if (!StringUtils.isNotEmpty(imageUrlNo)) {
                //全部上传成功
                return AjaxResult.success(imageUrl);
            }
            return AjaxResult.success(imageUrl);
        }
    }

    /**
     * 上传文件七牛云
     *
     * @param files
     * @return
     */
    @RequestMapping(value = "/imgs", method = RequestMethod.POST)
    public ApiReturnObject uploadImg(@RequestParam("file") MultipartFile[] files) {
        logger.error("上传接口");
        // 返回类型可以自己定义
        String serviceResult = null;
        // 验证非空
        if (files.length == 0) {
            serviceResult = "上传不能为空";
        } else {
            Map<String, List<String>> map = new HashMap<>(1);

            map = fileService.uploadImgs(files);

            List<String> resultList = map.get("result");
            logger.error("图片上传返回结果:" + resultList);

            if ("error".equals(resultList.get(0))) {
                return new ApiReturnObject("500", "上传错误", null);
            } else {
                return new ApiReturnObject("200", "上传成功", resultList);
            }
        }
        return null;
    }


    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        //获得上传文件的名称
        String name = file.getOriginalFilename();
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("请选择文件");
        }
        //生成唯一文件名称  并拼接上传文件的名称
        String fileName = QiniuUtil.getFileName(file);
        try {
            QiniuUtil.upload2Qiniu(file.getBytes(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }


    /**
     * 上传图片文件七牛云
     *
     * @param file
     * @return
     */
    @PostMapping("/imgupload")
    public ApiReturnObject uploadImgs(@RequestParam("file") MultipartFile[] file) {
        // 返回类型可以自己定义
        String serviceResult = null;
        // 验证非空
        if (StringUtils.isBlank(file[0].getOriginalFilename())) {
            serviceResult = "上传不能为空";
        } else {
            Map<String, List<String>> map = new HashMap<>();

            map = fileService.uploadImgs2(file[0]);

            List<String> resultList = map.get("result");
            logger.info("图片上传返回结果:" + resultList);

            if ("error".equals(resultList.get(0))) {
                return new ApiReturnObject("500", "上传错误", null);
            } else {
                return new ApiReturnObject("200", "上传成功", resultList);
            }
        }
        return null;
    }

    /**
     * 上传base64图片文件七牛云
     *
     * @param
     * @return
     */
    @PostMapping("/base64upload")
    public ApiReturnObject uploadBase64Img(@RequestBody FileUpload fileUpload) {
        String files = fileUpload.getName();
        MultipartFile file = MultipartFileUtils.base64MutipartFile(files);
        // 返回类型可以自己定义
        String serviceResult = null;
        // 验证非空
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            serviceResult = "上传不能为空";
        } else {
            Map<String, List<String>> map = new HashMap<>();

            map = fileService.uploadImgs2(file);

            List<String> resultList = map.get("result");
            logger.info("图片上传返回结果:" + resultList);

            if ("error".equals(resultList.get(0))) {
                return new ApiReturnObject("500", "上传错误", null);
            } else {
                return new ApiReturnObject("200", "上传成功", resultList);
            }
        }
        return null;
    }


    /**
     * 上传图片并添加数据
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImgAndAdd")
    public ApiReturnObject uploadImgAndAdd(@RequestParam("file") MultipartFile[] file,
                                           @RequestParam("type") String type,
                                           @RequestParam("catalogId") Integer catalogId) {
        // 返回类型可以自己定义
        String serviceResult = null;
        // 验证非空
        if (StringUtils.isBlank(file[0].getOriginalFilename())) {
            serviceResult = "上传不能为空";
        } else {
            Map<String, List<String>> map = new HashMap<>();
            map = fileService.uploadImgs2(file[0]);
            List<String> resultList = map.get("result");
            if ("error".equals(resultList.get(0))) {
                return new ApiReturnObject("500", "上传错误", null);
            } else {
                //调用添加接口  type  catalogId
                resourceFeign.add2(file[0].getOriginalFilename(), resultList.get(0), type, catalogId);
                return new ApiReturnObject("200", "上传成功", resultList);
            }
        }
        return null;
    }

    /**
     * 上传图片并添加数据
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadVideoAndAdd")
    public ApiReturnObject uploadVideoAndAdd(@RequestParam("file") MultipartFile[] file,
                                             @RequestParam("type") String type,
                                             @RequestParam("id") Integer id) {
        // 返回类型可以自己定义
        String serviceResult = null;
        // 验证非空
        if (StringUtils.isBlank(file[0].getOriginalFilename())) {
            serviceResult = "上传不能为空";
        } else {
            Map<String, List<String>> map = new HashMap<>();
            map = fileService.uploadImgs2(file[0]);
            List<String> resultList = map.get("result");
            if ("error".equals(resultList.get(0))) {
                return new ApiReturnObject("500", "上传错误", null);
            } else {
                //调用添加3d flash 接口  文件名称   上传返回名称  类型   resourceId
                ApiReturnObject apiReturnObject = resourceFeign.videoAdd(id, type, resultList.get(0), file[0].getOriginalFilename());
                if ("200".equals(apiReturnObject.getCode())) {
                    return new ApiReturnObject("200", "上传成功", resultList);
                }
            }
        }
        return null;
    }


    /**
     * 上传本地文件到七牛云服务器
     */
    @GetMapping("/uploadLocalFile")
    public String uploadLocalFile() {
        File file = new File("E:\\华为云服务器资源下载\\jr");
        //获取文件夹下所有文件
        File[] files = file.listFiles();
        if (files == null) {
            System.out.println("failed");
            return "文件夹无文件";
        }
        int i = 0;
        QiniuUtil qiniuUtil = new QiniuUtil();
        //遍历 匹配
        for (File file1 : files) {
            if (file1.isDirectory()) {
                continue;
            }
            //判断七牛云是否存在该文件
            if (QiniuUtil.estimateIsExist(file1.getName())) {
                System.out.println(i + " 该文件已存在：" + file1.getName());
            } else {
                //将该文件进行上传
                String s = qiniuUtil.uoloapQiniu(file1, file1.getName());
                if (StringUtil.isNotEmpty(s)) {
                    System.out.println(i + " 上传完成：" + file1.getName());
                }
            }
            try {
                Thread.sleep(10);
                System.out.println("继续！！！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
        }
        return "执行完毕！！！";
    }


}
